from datetime import datetime

from typing import Any, Optional, Union
from uuid import uuid4
from pydantic import BaseModel, Field


class ResponseMetadata(BaseModel):
    RequestId: str = Field(default_factory=lambda: str(uuid4()))
    Action: str
    Version: str = "v1"
    Service: str = "CDH"


class ErrorResponse(BaseModel):
    Code: str
    Message: str
    Detail: Optional[str] = None


class StandardResponse(BaseModel):
    ResponseMetadata: ResponseMetadata
    Result: Optional[Any] = None
    Error: Optional[ErrorResponse] = None

    @classmethod
    def success(
        cls,
        result: Any = None,
        *,
        request_id: str,
        action: str,
        version: str = "v1",
        service: str = "CDH"
    ) -> "StandardResponse":
        return cls(
            ResponseMetadata=ResponseMetadata(
                RequestId=request_id,
                Action=action,
                Version=version,
                Service=service
            ),
            Result=result
        )

    @classmethod
    def error(
        cls,
        code: str,
        message: str,
        detail: Optional[str] = None,
        *,
        request_id: str,
        action: str,
        version: str = "v1",
        service: str = "CDH"
    ) -> "StandardResponse":
        return cls(
            ResponseMetadata=ResponseMetadata(
                RequestId=request_id,
                Action=action,
                Version=version,
                Service=service
            ),
            Error=ErrorResponse(Code=code, Message=message, Detail=detail)
        )


class OperationResult(BaseModel):
    message: str = Field(default="ok", description="操作提示信息")


class AuditInfo(BaseModel):
    actor: str = Field(default="system")
    timestamp: datetime = Field(default_factory=datetime.utcnow)
